<template>
  <div class="sales-report">
    <div class="page-header">
      <h2>销售报表</h2>
      <div class="date-filter">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="loadReportData"
        />
      </div>
    </div>

    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">总销售额</div>
              <div class="stat-value">¥{{ totalSales.toFixed(2) }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">订单数量</div>
              <div class="stat-value">{{ totalOrders }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">平均订单金额</div>
              <div class="stat-value">¥{{ averageOrderAmount.toFixed(2) }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">会员消费占比</div>
              <div class="stat-value">{{ memberConsumptionRatio.toFixed(1) }}%</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>每日销售额趋势</span>
            </template>
            <div class="chart-container">
              <div ref="salesChart" style="height: 300px; width: 100%;"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>商品销售排行</span>
            </template>
            <div class="chart-container">
              <div ref="productChart" style="height: 300px; width: 100%;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="table-section">
      <el-card>
        <template #header>
          <span>销售明细</span>
        </template>
        <el-table :data="salesDetails" style="width: 100%" v-loading="loading">
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="orderCount" label="订单数" width="100" />
          <el-table-column prop="totalSales" label="销售额" width="120">
            <template #default="scope">
              ¥{{ scope.row.totalSales.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="memberSales" label="会员消费" width="120">
            <template #default="scope">
              ¥{{ scope.row.memberSales.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="nonMemberSales" label="非会员消费" width="120">
            <template #default="scope">
              ¥{{ scope.row.nonMemberSales.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="averageOrder" label="平均订单" width="120">
            <template #default="scope">
              ¥{{ scope.row.averageOrder.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

export default {
  name: 'SalesReport',
  setup() {
    const loading = ref(false)
    const dateRange = ref([])
    const salesData = ref([])
    const salesDetails = ref([])
    const salesChart = ref(null)
    const productChart = ref(null)
    let salesChartInstance = null
    let productChartInstance = null

    const totalSales = computed(() => {
      return salesData.value.reduce((sum, item) => sum + item.totalSales, 0)
    })

    const totalOrders = computed(() => {
      return salesData.value.reduce((sum, item) => sum + item.orderCount, 0)
    })

    const averageOrderAmount = computed(() => {
      return totalOrders.value > 0 ? totalSales.value / totalOrders.value : 0
    })

    const memberConsumptionRatio = computed(() => {
      const memberSales = salesData.value.reduce((sum, item) => sum + item.memberSales, 0)
      return totalSales.value > 0 ? (memberSales / totalSales.value) * 100 : 0
    })

    const loadReportData = async () => {
      loading.value = true
      try {
        const startDate = dateRange.value?.[0]?.toISOString().split('T')[0] || ''
        const endDate = dateRange.value?.[1]?.toISOString().split('T')[0] || ''
        
        const response = await fetch(`/api/reports/sales?startDate=${startDate}&endDate=${endDate}`)
        const data = await response.json()
        salesData.value = data
        salesDetails.value = data
        await nextTick()
        initCharts()
      } catch (error) {
        ElMessage.error('加载报表数据失败')
        // 使用模拟数据
        salesData.value = generateMockData()
        salesDetails.value = salesData.value
        await nextTick()
        initCharts()
      } finally {
        loading.value = false
      }
    }

    const generateMockData = () => {
      const data = []
      const today = new Date()
      for (let i = 6; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(date.getDate() - i)
        const totalSales = Math.random() * 5000 + 1000
        const memberSales = totalSales * (0.6 + Math.random() * 0.3)
        data.push({
          date: date.toISOString().split('T')[0],
          orderCount: Math.floor(Math.random() * 50) + 20,
          totalSales: totalSales,
          memberSales: memberSales,
          nonMemberSales: totalSales - memberSales,
          averageOrder: totalSales / (Math.floor(Math.random() * 50) + 20)
        })
      }
      return data
    }

    const initCharts = () => {
      try {
        // 清理旧的图表实例
        if (salesChartInstance) {
          salesChartInstance.dispose()
          salesChartInstance = null
        }
        if (productChartInstance) {
          productChartInstance.dispose()
          productChartInstance = null
        }

        // 销售额趋势图
        if (salesChart.value && salesData.value.length > 0) {
          salesChartInstance = echarts.init(salesChart.value)
          const option = {
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: salesData.value.map(item => item.date)
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '销售额',
                type: 'line',
                data: salesData.value.map(item => item.totalSales),
                smooth: true
              }
            ]
          }
          salesChartInstance.setOption(option)
        }

        // 商品销售排行图
        if (productChart.value) {
          productChartInstance = echarts.init(productChart.value)
          const mockProductData = [
            { name: '可口可乐', value: 1200 },
            { name: '百事可乐', value: 980 },
            { name: '康师傅方便面', value: 850 },
            { name: '统一老坛酸菜面', value: 720 },
            { name: '农夫山泉', value: 650 }
          ]
          const option = {
            tooltip: {
              trigger: 'item'
            },
            series: [
              {
                name: '销售额',
                type: 'pie',
                radius: '50%',
                data: mockProductData
              }
            ]
          }
          productChartInstance.setOption(option)
        }
      } catch (error) {
        console.error('初始化图表失败:', error)
      }
    }

    onMounted(() => {
      // 设置默认日期范围为最近7天
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      dateRange.value = [start, end]
      
      loadReportData()
    })

    onUnmounted(() => {
      // 清理图表实例
      if (salesChartInstance) {
        salesChartInstance.dispose()
        salesChartInstance = null
      }
      if (productChartInstance) {
        productChartInstance.dispose()
        productChartInstance = null
      }
    })

    return {
      loading,
      dateRange,
      salesData,
      salesDetails,
      salesChart,
      productChart,
      totalSales,
      totalOrders,
      averageOrderAmount,
      memberConsumptionRatio,
      loadReportData
    }
  }
}
</script>

<style scoped>
.sales-report {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 10px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-section {
  margin-bottom: 20px;
}
</style> 